package com.qubuyer.business.mine.viewmodel

import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.AbsoluteSizeSpan
import com.qubuyer.core.ext.dp
import com.qubuyer.core.ext.format
import com.qubuyer.core.ext.numberFormat
import com.qubuyer.core.framework.BaseModel
import com.qubuyer.core.http.HttpResult
import com.qubuyer.repository.entitys.IncomeEntity
import com.qubuyer.repository.entitys.RebateOrderEntity
import com.qubuyer.repository.entitys.SaleAmountEntity
import com.qubuyer.repository.entitys.WalletInfoEntity
import com.qubuyer.repository.services.ApiService

class WalletModel : BaseModel() {
    private val api: ApiService by injectApi()

    suspend fun getWalletInfo(): HttpResult<WalletInfoEntity?> {
        return api.walletInfo()
    }

    suspend fun withdraw(
        money: String,
        oauth: String,
        mobile: String,
        code: String
    ): HttpResult<String?> {
        return api.withdrawalApply(money, oauth, mobile, code)
    }

    suspend fun loadIncome(page: Int, type: String? = null): HttpResult<List<IncomeEntity>?> {
        return api.loadIncome(page,type)
    }

    suspend fun loadRebateOrderList(page: Int, type: Int): HttpResult<List<RebateOrderEntity>?> {
        return api.loadRebateOrderList(page,type).apply {
            if(this.ok() && !this.data.isNullOrEmpty()){
                this.data?.forEach {
                    it.item_total_amount = it.total_amount.format(2).toString()
                    it.item_expect_price = "${if(type == 1) "折让:¥" else "预计最高收益:¥"}${it.expect_price.numberFormat(2)}"
                }
            }
        }
    }

    suspend fun loadRebateOrderDetail(id: Int): HttpResult<RebateOrderEntity?> {
        return api.loadRebateOrderDetail(id).apply {
            this.data?.apply {
                detail_label_text = SpannableStringBuilder()
                    .append("当前折让金额",AbsoluteSizeSpan(12.dp), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                    .append(current_price.numberFormat(2),AbsoluteSizeSpan(56.dp), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                    .append("元",AbsoluteSizeSpan(14.dp), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                item_member_goods_price = "¥" + member_goods_price.numberFormat(2)
            }
        }
    }

    suspend fun restoreBalance(id: Int): HttpResult<String?> {
        return api.restoreBalance(id)
    }

    suspend fun loadSaleAmount(page: Int, type: Int): HttpResult<SaleAmountEntity?> {
        return api.loadSaleAmount(page,type)
    }
}